#include "reactor.hpp"
#include <cstring>
#include <algorithm>
#include <unistd.h>

Reactor::Reactor()
{
    epfd = epoll_create(1);     // arg will be ingored by kernel
}

Reactor::~Reactor()
{
    { if (epfd > 0) close(epfd); }
}

void Reactor::Poll(std::vector<int>& readyfd)
{
    int num = epoll_wait(epfd, events, 1024, 10);
    if (num > 0)
    {
        for (size_t i = 0; i < num; i++)
        {
            readyfd.push_back(events[i].data.fd);
        }
    }
}
void Reactor::AddFd(int fd, int event)
{
    struct epoll_event epevt;
    bzero(&epevt, sizeof epevt);
    epevt.data.fd = fd;
    epevt.events = event;     // default LT
    epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &epevt);
}
void Reactor::RmvFd(int fd)
{
    struct epoll_event epevt;
    bzero(&epevt, sizeof epevt);
    epevt.data.fd = fd;
    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &epevt);
}
void Reactor::ModFd(int fd, int event)
{
    struct epoll_event epevt;
    bzero(&epevt, sizeof epevt);
    epevt.data.fd = fd;
    epevt.events = event;     // default LT
    epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &epevt);
}